/**
 * @开发版权 
 * @项目名称 VFCloud-PaaS
 * @版本信息 v1.0
 * @开发人员 zhous
 * @开发日期 2023-02-21
 * @修订日期
 * @描述  ApplicationReadyEventListener
 */
package com.vf.cloud.paas.common.listener;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
import com.jfinal.kit.StrKit;
import com.vf.cloud.paas.app.agent.common.client.RenderClient;
import com.vf.cloud.paas.app.master.common.domain.User;
import com.vf.cloud.paas.app.master.common.server.agentManager.AgentManagerServer;
import com.vf.cloud.paas.app.master.common.server.ueManager.UEManagerServer;
import com.vf.cloud.paas.common.cirrus.Cirrus;
import com.vf.cloud.paas.common.util.EncryptUtil;
import com.vf.cloud.paas.common.util.SpringContextHolder;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class ApplicationReadyEventListener implements ApplicationListener<ApplicationReadyEvent> {

	@Value("${agent.token}")
	private String agentToken;

	@Value("${agent.enabled}")
	private boolean agentEnabled;

	@Value("${master.enabled}")
	private boolean masterEnabled;
	
	@Value("${agent.project.path}")
	private String projectPath;

	@Override
	public void onApplicationEvent(ApplicationReadyEvent contextReadyEvent) {

		if (agentEnabled) {
			Cirrus.agentToken = agentToken;

			if (StrKit.isBlank(agentToken)) {
				log.info(String.format("AgentToken is null .", "failed"));
				return;
			}
			Cirrus.renderClient = SpringContextHolder.getBean(RenderClient.class);
			Cirrus.renderClient.run();
			
		}

		if (masterEnabled) {
			User user = User.dao.findById("1");
			if (user == null) {
				user = new User();
				user.setId("1");
				user.setPid("-1");
				user.setName("超级管理员");
				user.setUsername("administrator");
				user.setPassword(EncryptUtil.encrypt("administrator"));
				user.setRoleMark("admin");
				user.setIsLimit("-1");
				user.save();
			}

			Cirrus.agentManagerServer = SpringContextHolder.getBean(AgentManagerServer.class);
			Cirrus.agentManagerServer.run();
			
			Cirrus.ueManagerServer = SpringContextHolder.getBean(UEManagerServer.class);
			Cirrus.ueManagerServer.run();
			
		}

	}

}
